var bg = chrome.extension.getBackgroundPage();
var Options = bg.Options;
var DomainsInfo = bg.DomainsInfo;
var DomainStatus = bg.DomainStatus;

var UI = 
{
	Frame : 
	{
		Content: document.getElementById("content_container"), 
		ContentTitle: document.getElementById("content_title"), 
		NavigationList: document.getElementById("navigation_list"), 
	}, 
	General : 
	{
		DomainPreference_AutoDetect: document.getElementById(
			"domain_preference_autodetect"), 
		DomainPreference_AlwaysExternal: document.getElementById(
			"domain_preference_alwaysexternal"), 
		DomainPreference_Custom: document.getElementById(
			"domain_preference_custom"), 
	}, 
	UI : 
	{
	}, 
	Blocking : 
	{
		//Since they're all lists, see also UI.Lists
	}, 
	Notifications : 
	{
		UpdateUnreadMessage: document.getElementById(
			"options_notifications_updatemessage"), 
		NewMessageNotification: document.getElementById(
			"options_notifications_message"), 
	}, 
	Labs : 
	{
		HomepageUpdate: document.getElementById(
			"options_ui_homepage_update"), 
		HomepageUpdateInterval: document.getElementById(
			"options_ui_homepage_update_interval"), 
	}, 
	
	Notes:
	{
		options_general_stay_signedin: document.getElementById(
			"options_general_stay_signedin_warning"), 
		options_ui_hidehotlist2: document.getElementById(
			"options_ui_hidehotlist2_note"), 
	}, 
	Lists:
	[
		{
			element: document.getElementById("options_blocking_posts"), 
			option: Options.Blocking, 
			property: "PostsByUsers", 
		}, 
		{
			element: document.getElementById(
				"options_blocking_signatures"), 
			option: Options.Blocking, 
			property: "SignaturesOfUsers", 
		}, 
		{
			element: document.getElementById("options_blocking_photos"), 
			option: Options.Blocking, 
			property: "PhotosOfUsers", 
		}, 
		{
			element: document.getElementById("options_blocking_images"), 
			option: Options.Blocking, 
			property: "ImagesInPostsByUsers", 
		}, 
		{
			element: document.getElementById("options_blocking_forums"), 
			option: Options.Blocking, 
			property: "PostsFromForums", 
		}, 
	], 
	Checkboxes:
	[
		{
			input: document.getElementById(
				"options_general_stay_signedin"), 
			option: Options.SignIn, 
			property: "StaySignedIn", 
		}, 
		{
			input: document.getElementById(
				"options_general_signin_nowait"), 
			option: Options.SignIn, 
			property: "NoWaitAfterSignIn", 
		}, 
		{
			input: document.getElementById(
				"options_ui_hidehotlist2"), 
			option: Options.UI, 
			property: "HideHotlist2", 
		}, 
		{
			input: document.getElementById(
				"options_ui_simpleread"), 
			option: Options.UI, 
			property: "SimpleRead", 
		}, 
		{
			input: document.getElementById(
				"options_ui_hotlist_hideauthors"), 
			option: Options.UI, 
			property: "HideAuthorsInHotlist", 
		}, 
		{
			input: document.getElementById(
				"options_ui_showip"), 
			option: Options.UI, 
			property: "ShowIP", 
		}, 
		{
			input: document.getElementById(
				"options_ui_replyandat"), 
			option: Options.UI, 
			property: "ReplyAndAt", 
		}, 

	], 
};

UI.General.UpdateDomain = (function()
{
	if(Options.Domain.Preference == "autoDetect")
		bg.UpdateDetectedDomain();
	else if(Options.Domain.Preference == "alwaysExternal")
		Options.Domain.Current = Options.Domain.PreferredExternalDomain;
});

UI.General.ShowNetworkStatus = (function()
{
	var cur_text;
	if(DomainStatus["bbs.stuhome.net"] == "ok")
		cur_text = document.getElementById("internal_text");
	else if(DomainStatus["bbs.stuhome.net"] == "unavailable")
		cur_text = document.getElementById("external_text");
	if(cur_text)
	{
		cur_text.style.fontWeight = "bold";
		cur_text.style.color = "#0000ff";
	}
});

UI.General.InitDomainPreference = (function()
{
	var domain_prefs = 
	{
		"autoDetect": UI.General.DomainPreference_AutoDetect, 
		"alwaysExternal": UI.General.DomainPreference_AlwaysExternal, 
		"custom": UI.General.DomainPreference_Custom
	};
	for(var pref in domain_prefs)
	{
		if(Options.Domain.Preference == pref)
			domain_prefs[pref].checked = true;
		domain_prefs[pref].onchange = (function(e)
		{
			if(this.checked)
			{
				Options.Domain.Preference = this.value;
				UI.General.UpdateDomain();
				GA.TrackCheckbox(e);
			}
		});
	}
});

UI.General.InitDomains = (function()
{
	for(var cur in DomainsInfo)
	{
		var type = DomainsInfo[cur];
		if(type == "internal" || type == "external")
		{
			var div = document.getElementById(type + "_domains");
			var input = document.createElement("input");
			input.type = "radio";
			input.name = type; // also used in the handler of onchange
			input.value = cur;
			input.id = type + "_domain_" + cur;
			input.checked = (type == "internal" ? 
				Options.Domain.PreferredInternalDomain : 
				Options.Domain.PreferredExternalDomain) == cur;
			input.onchange = (function(e)
			{
				if(this.name == "internal")
					Options.Domain.PreferredInternalDomain = this.value;
				else if(this.name == "external")
					Options.Domain.PreferredExternalDomain = this.value;
				UI.General.UpdateDomain();
				GA.TrackCheckbox(e);
			});
			div.appendChild(input);
			var label = document.createElement("label");
			label.setAttribute("for", input.id);
			if(cur == Options.Domain.Current)
				label.style.fontWeight = "bold";
			label.appendChild(document.createTextNode(cur));
			div.appendChild(label);
		}
	}
});

UI.General.InitDomainOptions = (function()
{
	UI.General.ShowNetworkStatus();
	UI.General.InitDomainPreference();
	UI.General.InitDomains();
});

UI.InitCheckboxes = (function()
{
	for(var i = 0; i < UI.Checkboxes.length; ++i)
	{
		var cur = UI.Checkboxes[i];
		cur.input._tag_id = i;
		cur.input.onchange = (function(e)
		{
			(UI.Notes[this.id] || {style:{}}).style.display = 
				this.checked ? "" : "none";
			UI.Checkboxes[this._tag_id].option._setProperty(
				UI.Checkboxes[this._tag_id].property, this.checked);
			GA.TrackCheckbox(e);
		});
		cur.input.checked = cur.option._getProperty(cur.property);
		cur.input.onchange();
	}
});

UI.InitLists = (function() //Initialize lists in blocking options
{
	function DumpList(div)
	{
		var list = [];
		for(var i = 0; i < div.children.length; ++i)
		{
			var cur = div.children[i];
			if(cur.tagName.toLowerCase() == "input" && cur.type == "text")
			{
				var text = cur.value;
				var items = text.split(/[\s,]+/);
				for(var j = 0; j < items.length; ++j)
					if(items[j])
						list[list.length] = items[j];
			}
		}
		_gaq.push(['_trackEvent', div.id, list.length.toString()]);
		return list;
	}

	function SaveOptions()
	{
		for(var i = 0; i < UI.Lists.length; ++i)
		{
			var cur = UI.Lists[i];
			cur.option._setProperty(cur.property, DumpList(cur.element));
		}
	}

	function AppendInput(parent_element, sibling, value)
	{
		var input = document.createElement("input");
		input.type = "text";
		value && (input.value = value);
		input.oninput = (function()
		{
			this.style.fontWeight = "bold";
			if(!this.nextElementSibling)
				AppendInput(null, this);
		});
		input.onblur = (function()
		{
			SaveOptions();
			this.style.fontWeight = "";
		});
		(parent_element || sibling.parentElement).appendChild(input);
	}

	for(var i = 0; i < UI.Lists.length; ++i)
	{
		var cur = UI.Lists[i];
		var value = cur.option._getProperty(cur.property);
		for(var j = 0; j < value.length; ++j)
			AppendInput(cur.element, null, value[j]);
		AppendInput(cur.element);
	}
});

(function () //Initialize navigation
{
	var options = UI.Frame.Content.children;
	var navigation_list = UI.Frame.NavigationList;
	var url_hash = location.hash.substr(1);

	for(var i = 0; i < options.length; ++i)
	{
		var cur = options[i];

		//options.html: <div id="options_xxxxxx" ...
		var id = cur.id.match(/^options_(.*)$/)[1];
		var title = cur.title;

		// Hide LABS by default. To show it, append #labs in the URL.
		if(id == "labs" && url_hash != "labs")
			continue;

		var li = document.createElement("li");
		var a = document.createElement("a");
		a.appendChild(document.createTextNode(title));
		a.href = "#" + id;
		a.title = title;
		a.onclick = (function()
		{
			//When the function is called, the navigation list may not 
			//have been completely constructed.
			var navs = navigation_list.children;
			for(var i = 0; i < options.length && i < navs.length; ++i)
			{
				if(options[i].title == this.title)
				{
					options[i].style.display = "";
					navigation_list.children[i].style.fontWeight = "bold";
				}
				else
				{
					options[i].style.display = "none";
					navigation_list.children[i].style.fontWeight = "";
				}
			}
			UI.Frame.ContentTitle.innerText = this.title;
		});
		li.appendChild(a);
		navigation_list.appendChild(li);
		if(i == 0 || url_hash == id)
			a.onclick();
	}
})();

(function (){

UI.General.InitDomainOptions();
UI.InitCheckboxes();
UI.InitLists();

UI.Labs.HomepageUpdate.checked = Options.UI.HomepageUpdateInterval != 0;
UI.Labs.HomepageUpdateInterval.value = 
	Options.UI.HomepageUpdateInterval || 10;
UI.Labs.HomepageUpdate.onchange = UI.Labs.HomepageUpdateInterval.oninput = 
(function(e)
{
	if(UI.Labs.HomepageUpdate.checked)
	{
		var interval = parseInt(UI.Labs.HomepageUpdateInterval.value);
		Options.UI.HomepageUpdateInterval = 
			(interval >= 10) ? interval : 10;
	}
	else
		Options.UI.HomepageUpdateInterval = 0;
	if(this.id == UI.Labs.HomepageUpdate.id)
		GA.TrackCheckbox(e);
});

UI.Notifications.UpdateUnreadMessage.checked = 
	Options.Notifications.UpdateUnreadMessageInterval != 0;
UI.Notifications.NewMessageNotification.checked = 
	Options.Notifications.NewMessageNotification;
UI.Notifications.NewMessageNotification.disabled = 
	!UI.Notifications.UpdateUnreadMessage.checked;
UI.Notifications.UpdateUnreadMessage.onchange = (function(e)
{
	Options.Notifications.UpdateUnreadMessageInterval = this.checked ? 
		60 : 0;
	UI.Notifications.NewMessageNotification.disabled = !this.checked;
	GA.TrackCheckbox(e);
});
UI.Notifications.NewMessageNotification.onchange = (function(e)
{
	Options.Notifications.NewMessageNotification = this.checked;
	GA.TrackCheckbox(e);
});

})();

